'use strict';

const Service = require('egg').Service;

class user extends Service {
  // 登录
  async login(username, password) {
    const { app } = this;
    const query = await app.mysql.get('user', { username });
    if (!query) {
      return 'no exists';
    }
    const result = await app.mysql.get('user', {
      username,
      password,
    });
    return result;
  }

  // 注册
  async register(username, password, role, nickname, phone, email) {
    const { app } = this;
    const data = {
      username,
      password,
      role,
      create_time: Date.now(),
    };
    if (app.validate(nickname).hasString()) {
      data.nickname = nickname;
    }
    if (app.validate(phone).int()) {
      data.phone = Number(phone);
    }
    if (app.validate(email).hasString()) {
      data.email = email;
    }
    const query = await app.mysql.get('user', { username });
    if (query) {
      return 'exists';
    }
    const result = await app.mysql.insert('user', JSON.parse(JSON.stringify(data)));
    return result;
  }

  // 修改账号
  async update(id, username, password, role) {
    const { app } = this;
    const data = {
      username,
      password,
      role,
      modify_time: Date.now(),
    };
    const result = await app.mysql.update('user', data, {
      where: { id },
    });
    if (result.changedRows) {
      return true;
    }
  }

  // 用户信息
  async userinfo(id) {
    const { app } = this;
    const result = await app.mysql.get('user', { id });
    if (result) {
      delete result.password;
      delete result.create_time;
      delete result.modify_time;
      const role = await app.mysql.get('role', { type: result.role });
      if (role) {
        result.roleName = role.name;
      }
    }
    return result;
  }
}

module.exports = user;
